package com.work.formaldehyde.activity;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activityadapter.AddressManagesAdapter;
import com.work.formaldehyde.model.GetAddressModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SelectAddressjiesuanActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView city_comeback;
    private RelativeLayout submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 0);
        setContentView(R.layout.activity_getaddress);
        city_comeback = findViewById(R.id.city_comeback);
        city_comeback.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(SelectAddressjiesuanActivity.this))
            inti();
    }

    private ArrayList<GetAddressModel.data> new_list_view;
    private ListView city_manage_list;
    public AddressManagesAdapter myAdapter;
    private GetAddressModel getAddressModel;

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 初始加载视图
     */
    public void Init() {
        city_manage_list = findViewById(R.id.city_manage_list);
        new_list_view = new ArrayList<>();
        okHttp_postFromParameters();
        city_manage_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GouWuCheJieSuanActivity.addrestr = new_list_view.get(position).getConsignee_city() + new_list_view.get(position).getConsignee_addr();
                GouWuCheJieSuanActivity.namestr = new_list_view.get(position).getConsignee_name();
                GouWuCheJieSuanActivity.phonestr = new_list_view.get(position).getConsignee_phone();
                onBackPressed();
            }
        });
        submit = findViewById(R.id.submit);
        submit.setOnClickListener(this);
    }

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        Init();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!Url.USER_ID.equals("") && ApiUtils.isNetworkConnected(SelectAddressjiesuanActivity.this)) {
            ApiUtils.windows(SelectAddressjiesuanActivity.this, city_comeback, "请稍后");
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    ApiUtils.closepopup();
                }
            }, 10000);
            okHttp_postFromParameters();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.city_comeback:
                onBackPressed();
                break;
            case R.id.submit:
                if (Url.USER_ID.equals("")) {
                    Intent is_login = new Intent(SelectAddressjiesuanActivity.this, LoginActivity.class);
                    startActivity(is_login, ActivityOptions.makeSceneTransitionAnimation(SelectAddressjiesuanActivity.this).toBundle());
                    ApiUtils.SetToast(SelectAddressjiesuanActivity.this, "请先登录");
                } else {
                    Intent toaddress = new Intent(SelectAddressjiesuanActivity.this, AddressActivity.class);
                    toaddress.putExtra("opentype", "0");
                    startActivity(toaddress, ActivityOptions.makeSceneTransitionAnimation(SelectAddressjiesuanActivity.this).toBundle());
                }
                break;
        }
    }

    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN)
//                            .build();
//                    Request request = new Request.Builder().url(Url.GETADDRESSLIST).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot1.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.GETADDRESSLIST + "?uid=" + Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot1.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot1 = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                ApiUtils.closepopup();
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        getAddressModel = gson.fromJson(msg.obj.toString(),
                                GetAddressModel.class);
                        new_list_view.clear();
                        new_list_view.addAll(getAddressModel.getData());
                        myAdapter = new AddressManagesAdapter(new_list_view,
                                SelectAddressjiesuanActivity.this, SelectAddressjiesuanActivity.this);
                        city_manage_list.setAdapter(myAdapter);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


}
